package com.network;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.network.NetConstantsKt.URL_DEFAULT;

/**
 * <pre>
 *     author : Roacher
 *     time   : 2017/12/14
 *     desc   :
 *     version: 1.0
 * </pre>
 */
//创建枚举默认就是线程安全的，所以不需要担心double checked locking，而且还能防止反序列化导致重新创建新的对象。但是还是很少看到有人这样写，可能是因为不太熟悉吧。

public enum RetrofitClient {
    INSTANCE;

    private final Retrofit retrofit;

    RetrofitClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new HeaderInterceptor());
        //设置超时
        builder.connectTimeout(60000, TimeUnit.SECONDS);
        builder.readTimeout(60000, TimeUnit.SECONDS);
        builder.writeTimeout(60000, TimeUnit.SECONDS);
        builder.hostnameVerifier(new AllowAllHostnameVerifier());
        //错误重连
        builder.retryOnConnectionFailure(true);

        retrofit = new Retrofit.Builder()
                .baseUrl(URL_DEFAULT)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build();
    }

    public Retrofit getRetrofit() {
        return retrofit;
    }
}
